#include <stdio.h>
#include <stdlib.h> //exit函数需调用的头文件
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>

int main(int argc, char* argv[]){
	if(argc == 3){
	  	int f1 = open(argv[1],O_RDONLY);
		if(f1 == -1) printf("file cannot found\n");
		else{
			struct stat buf;
			if(!stat(argv[1],&buf) && !S_ISDIR(buf.st_mode)){ //判断是否满足不是目录的条件
				int permission_num;
				permission_num = (!!(buf.st_mode&S_IRUSR))*400+(!!(buf.st_mode&S_IWUSR))*200+(!!(buf.st_mode&S_IXUSR))*100+(!!(buf.st_mode&S_IRGRP))*40+(!!(buf.st_mode&S_IWGRP))*20+(!!(buf.st_mode&S_IXGRP))*10+(!!(buf.st_mode&S_IROTH))*4+(!!(buf.st_mode&S_IWOTH))*2+(!!(buf.st_mode&S_IXOTH))*1;  //获取原文件权限
				//printf("%d\n",permission_num);
				int f2 = creat(argv[2], permission_num);  //为复制文件设置相同的权限
				int size;
				char str[16] = {0};
				while(size = read(f1,str,16)){  //循环读取
					write(f2,str,size);
				}
			}
			else{
				if(stat(argv[1],&buf) == -1){ perror(argv[1]); exit(1); }
				if(S_ISDIR(buf.st_mode)) printf("%s is a directory\n",argv[1]);
			}
		}
		close(f1);
	}
	else printf("format error\n");
	return 0;
}